package com.tedu.bank_ems1.dao.impl;

import com.tedu.bank_ems1.dao.DeptDao;
import com.tedu.bank_ems1.entity.Dept;
import com.tedu.bank_ems1.entity.Emp;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：毕龙
 * Date: 2024/6/25 15:05
 */
public class DeptDaoImpl implements DeptDao {
    @Override
    public List<Dept> listDept() {

        Connection conn = null;
        PreparedStatement pstm = null;
        ResultSet rs = null;
        ArrayList<Dept> list = null;
        try {
            //加载驱动
            //通过一个类的信息获取类对象 类加载
            Class.forName("com.mysql.cj.jdbc.Driver");

            //获取链接
            String url = "jdbc:mysql://localhost:3306/ems";
            String mysqlEmp = "root";
            String mysqlPass = "root";
            conn = DriverManager.getConnection(url, mysqlEmp, mysqlPass);

            //执行sql
            String sql = "select id,name from dept";
            pstm = conn.prepareStatement(sql);

            //处理查询结果
            rs = pstm.executeQuery();
            list = new ArrayList<>();
            while (rs.next()) {
                Dept dept = new Dept();
                dept.setId(rs.getInt(1))
                        .setName(rs.getString(2));
                list.add(dept);
            }


            //释放资源
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                rs.close();
                pstm.close();
                conn.close();
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }

        return list;
    }
}
